import React, { useEffect, useState } from 'react';
import { Modal, Form, Row, Col, Input } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import ASelect, { ASelectOptionType } from '@/components/SelfComp/ASelect';
import { AppItem } from '@/types/app';
import { DataItem, FlagEnum, FormModalProps } from '@/types/global';
import { TradeItem } from '@/types/trade';
import { formLayout, basicFormItemLangLayout, maxModalFormItemLayout } from '@/utils/commons';

type UpdateTradeProps<T> = FormModalProps<T> & {
  flag: FlagEnum;
  appList: AppItem[];
  systemData: DataItem[];
  clusterData: DataItem[];
}

const FormItem = Form.Item;

const UpdateTradeModal: React.FC<UpdateTradeProps<TradeItem>> = (props) => {

  // useForm 是 React Hooks 的实现，只能用于函数组件
  // formRef = Form.useForm;
  const [appData, setAppData] = useState<DataItem[]>([]);
  const [systemCode, setSystemCode] = useState<string>('');
  const formRef = React.createRef<FormInstance>();

  useEffect(() => {
    console.log('UpdateTradeModal.useEffect');
    const { appList, formData } = props;
    const { systemCode, clstCode } = formData;
    if (appList && appList.length > 0) {
      const appData: DataItem[] = [];
      appList.forEach(item => {
        const srcSystemCode = item.systemCode;
        const srcClstCode = item.cluster;
        if (systemCode === srcSystemCode && clstCode === srcClstCode) {
          const dataItem: DataItem = {
            key: item.appCode,
            value: item.appName
          }
          appData.push(dataItem);
        }
      });
      setAppData(appData);
    }
  }, [])

  const onOk = () => {
    const { formData, flag } = props;
    if (flag === 'view') {
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK(formData);
      }
    } else {
      const { tradeId } = formData;
      formRef.current!.validateFields().then(fieldsValue => {
        console.info(fieldsValue);
        const values = {
          ...fieldsValue,
          tradeId
        };
        console.log('Received values of form: ', values);
        const { onHandlerOK } = props;
        if (onHandlerOK) {
          onHandlerOK({
            ...values
          });
        }
      }).catch((err) => console.info('表单校验不通过'));
    }
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const {onHandlerCancel} = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 交易所属系统栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const systemCodeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // console.info('systemCodeChange');
    // 注意这里不能用resetFields，因为resetFields会将栏位重置成初始化值
    formRef.current!.setFieldsValue(
      {
        clstCode: '',
        appCode: ''
      }
    );
    // 其实可以筛选集群
    // 但这里暂时不做此功能
    setSystemCode(value);
  }

  /**
   * 交易所属集群栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const clstCodeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // console.info('clstCodeChange');
    formRef.current!.setFieldsValue(
      {
        appCode: ''
      }
    );
    // 根据全量的系统应用列表，所选的系统，集群，筛选应用列表
    const clstCode = value;
    const { appList } = props;
    if (appList && appList.length > 0) {
      const appData: DataItem[] = [];
      appList.forEach(item => {
        const srcSystemCode = item.systemCode;
        const srcClstCode = item.cluster;
        if (systemCode === srcSystemCode && clstCode === srcClstCode) {
          const dataItem: DataItem = {
            key: item.appCode,
            value: item.appName
          }
          appData.push(dataItem);
        }
      });
      setAppData(appData);
    }
  }

  const { formData, colon, modalWidth, modalVisible, systemData, clusterData, loading, flag } = props;
  const formItemLayout = basicFormItemLangLayout;
  const modalTitle = (flag === 'edit' ? '修改交易' : '查看交易信息');

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={12}>
            <FormItem label='交易功能码' name='funcCode' {...formItemLayout} colon={colon}
              rules={[
                { max: 20, message: '交易功能码最多允许输入20个字符' },
                { required: true, message: '交易功能码必输' }
              ]}
              initialValue={formData.funcCode}
            >
              <Input disabled/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='交易名称' name='funcName' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '交易名称最多允许输入30个字符' },
                { required: true, message: '交易名称必输' }
              ]}
              initialValue={formData.funcName}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <FormItem label='交易路径' name='funcAction' {...maxModalFormItemLayout} colon={colon}
              rules={[
                { max: 100, message: '交易路径最多允许输入100个字符' },
                { required: true, message: '交易路径必输' },
              ]}
              initialValue={formData.funcAction}
            >
              <Input/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='负责人' name='owner' {...formItemLayout} colon={colon}
              rules={[
                { max: 20, message: '负责人最多允许输入20个字符' },
                { required: true, message: '负责人必输' }
              ]}
              initialValue={formData.owner}
            >
              <Input/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='交易所属系统' name='systemCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属系统必输' }
              ]}
              initialValue={formData.systemCode}
            >
              <ASelect dataSource={systemData} onChange={systemCodeChange}/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='交易所属集群' name='clstCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属集群必输' }
              ]}
              initialValue={formData.clstCode}
            >
              <ASelect dataSource={clusterData} onChange={clstCodeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='交易所属应用' name='appCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属应用必输' }
              ]}
              initialValue={formData.appCode}
            >
              <ASelect dataSource={appData}/>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
}

export default UpdateTradeModal;